<template>
  <div class="default-main ba-table-box">
    <el-alert
      class="ba-table-alert"
      v-if="baTable.table.remark"
      :title="baTable.table.remark"
      type="info"
      show-icon
    />
    <!-- 表格顶部菜单 -->
    <TableHeader
      :buttons="['refresh', 'columnDisplay']"
      :quick-search-placeholder="placeholder"
      @action="baTable.onTableHeaderAction"
    />
    <Table ref="tableRef" @action="baTable.onTableAction" />
    <!-- 表单 -->
    <!-- <PopupForm v-if="baTable.form.operate ? true : false" ref="formRef" /> -->
  </div>
</template>
<script lang="ts" setup>
import {
  ref,
  reactive,
  provide,
  onMounted,
  onBeforeUnmount,
  inject,
} from "vue";
import baTableClass from "@/utils/baTable";
import { baTableApi, operatorShowOff } from "@/utils/common"; // 导入表格api方法生成器
import { BusinessFile } from "@/api/backend/index";
import Table from "@/components/table/index.vue";
import TableHeader from "@/components/table/header/index.vue";
import useCurrentInstance from "@/utils/useCurrentInstance";
import type { TableRow, TableColumn } from "@/utils/baTable"; //表格列行类型
import { useRoute, useRouter } from "vue-router";
import { useBusiness } from "@/store/backend/BusinessM/info";
import { useDictionary } from "@/store/backend/tool/dictionary";
import { getDictData } from "@/utils/common";
import _ from "lodash";
import { useLedgerFile } from "@/store/backend/BusinessM/file";

// import PopupForm from "./filePopupForm.vue";

const formRef = ref();
const placeholder = ref<string>("模糊搜索");
const tableRef = ref();
const route = useRoute();
const file = useLedgerFile();
const router = useRouter();
const business = useBusiness();
const dictionary = useDictionary();
const navTabs = inject("navTabs") as any;

const state: {
  orderId: any;
} = reactive({ orderId: 0 });

//全局事件总线
const { proxy } = useCurrentInstance();

//字段显隐记忆功能
const filedShowOff = (filter: any) => {
  if ((navTabs as any).columnDisplayStoreMap) {
    return (navTabs as any).columnDisplayStoreMap.get(
      route.path + "/" + filter
    );
  }
  return true;
};

// 每页个数记忆功能
const pageSizeKeep = () => {
  if ((navTabs as any).pageSizeMap) {
    return (navTabs as any).pageSizeMap.get(route.path + BusinessFile)
      ? (navTabs as any).pageSizeMap.get(route.path + BusinessFile)
      : 10;
  }
  return 10;
};

const baTable = new baTableClass(
  new baTableApi(BusinessFile), //该用户管理增删改查封装好的api
  {
    pk: "id",
    column: [
      { type: "selection", align: "center", operator: false },
      {
        show: filedShowOff("companyName"),
        label: "企业名称",
        prop: "companyName",
        align: "center",
        operator: false,
      },
      {
        show: filedShowOff("fileName"),
        label: "文件名称",
        prop: "fileName",
        align: "center",
        operator: false,
      },
      {
        show: filedShowOff("createTime"),
        label: "上传日期",
        prop: "createTime",
        align: "center",
        operator: false,
      },
      {
        label: "操作",
        align: "center",
        width: "130",
        render: "buttons",
        fixed: "right",
        buttons: [
          {
            render: "tipButton",
            name: "watch",
            title: "文件预览",
            text: "",
            type: "primary",
            icon: "iconfont icon-chubuhuizong",
            class: "table-row-edit",
            disabledTip: false,
            // 按钮是否显示，请返回布尔值
            display: (row: TableRow, field: TableColumn) => {
              return false;
            },
            // 按钮是否禁用，请返回布尔值
            disabled: (row: TableRow, field: TableColumn) => {
              return false;
            },
            attr: {},
          },
          {
            render: "tipButton",
            name: "editFile",
            title: "编辑",
            text: "",
            type: "primary",
            icon: "iconfont icon-pencil",
            class: "table-row-edit",
            disabledTip: false,
            // 按钮是否显示，请返回布尔值
            display: (row: TableRow, field: TableColumn) => {
              return false;
            },
            // 按钮是否禁用，请返回布尔值
            disabled: (row: TableRow, field: TableColumn) => {
              return false;
            },
            attr: {},
          },
          {
            render: "confirmButton",
            name: "removeFile",
            title: "删除",
            text: "",
            type: "danger",
            icon: "el-icon-DeleteFilled",
            class: "table-row-delete",
            popconfirm: {
              confirmButtonText: "删除",
              cancelButtonText: "取消",
              confirmButtonType: "danger",
              title: "确定删除所选项吗",
            },
            disabledTip: false,
            // 按钮是否显示，请返回布尔值
            display: (row: TableRow, field: TableColumn) => {
              return false;
            },
            // 按钮是否禁用，请返回布尔值
            disabled: (row: TableRow, field: TableColumn) => {
              return false;
            },
            attr: {},
          },
        ],
        operator: false,
      },
    ],
    filter: { companyId: route.query.companyId, pageSize: pageSizeKeep() },
    acceptQuery: false, //不接受url的query参数并自动触发通用搜索
  }
);

proxy.eventBus.on("changeFileId", (id: any) => {
  console.log("文件id", file.orderId, id);
  baTable.getList("");
});
//修改文件表单
const emit = defineEmits(["onPut"]);
const editFile = (name: string, row: anyObj) => {
  //将详情赋值给添加表单
  const newRow = _.cloneDeep(row);
  emit("onPut", newRow);
};
//删除定价
const deleteFile = (name: string, row: anyObj) => {
  file
    .deleteFile(row)
    .then((res) => {
      baTable.getList("");
    })
    .catch((err) => {
      baTable.getList("");
    });
};
//获取菜单状态的字典
const getMenuStatus = () => {
  dictionary.getDictInfo("device_online_status").then((res: any) => {
    // state.statusDict = getDictData(res);
    dictionary.tag = getDictData(res);
    console.log("获取菜单状态的字典", dictionary.tag);
  });
};
getMenuStatus();

onMounted(() => {
  console.log("当前路由", route.path);

  //全局事件总线
  const { proxy } = useCurrentInstance();
  //   proxy.eventBus.emit("pointer"); //el-table显示双击小手套
  //将table的ref给到table类
  baTable.table.ref = tableRef.value;
  baTable.mount();
  baTable.getList(BusinessFile);

  /**
   * 表格内的按钮响应
   * @param name 按钮name
   * @param row 被操作行数据
   */
  proxy.eventBus.on(
    "onTableButtonClick",
    (data: { name: string; row: TableRow }) => {
      console.log("data", data);
      if (data.name == "editFile") {
        //编辑
        file.opera = "edit";
        editFile(data.name, data.row);
      } else if (data.name == "removeFile") {
        //删除
        deleteFile(data.name, data.row);
      } else if (data.name == "watch") {
        window.open(data.row.fileUrl, "_blank"); //打开文件
      }
    }
  );
  console.log("router", router.currentRoute.value.path);
});

proxy.eventBus.on("pagesize", (res: any) => {
  console.log("pagesize", route.query);
  baTable.table.loading = true;
  file.pageSize = res.pageSize;
  file.geFileList().then((res: any) => {
    baTable.table.data = res.rows;
    baTable.table.total = res.total;
    baTable.table.loading = false;
  });
});
proxy.eventBus.on("pageNum", (res: any) => {
  console.log("pageNum", route.query);
  baTable.table.loading = true;
  file.pageNum = res.pageNum;
  file.geFileList().then((res: any) => {
    baTable.table.data = res.rows;
    baTable.table.total = res.total;
    baTable.table.loading = false;
  });
});

//刷新文件列表
proxy.eventBus.on("refreshFile", () => {
  baTable.getList("");
});

// 实例化表格后，将 baTable 的实例提供给上下文
provide("baTable", baTable);
provide("dictionary", dictionary);

onBeforeUnmount(() => {
  file.pageNum = 1;
  file.pageSize = 10;
  proxy.eventBus.off("pageNum");
  proxy.eventBus.off("pagesize");
  proxy.eventBus.off("changeFileId");
});
</script>
<style lang="scss" scoped>
.ba-operate-dialog {
  .ba-operate-form {
    .formTip {
      margin-left: 120px;
    }

    .el-form {
      :deep(.el-form-item__content) {
        margin-top: 10px;
      }
    }
  }
}

@media screen and (max-width: 460px) {
  .ba-operate-dialog {
    .ba-operate-form {
      .formTip {
        margin-left: 0px;
      }

      .el-form {
        :deep(.el-form-item__content) {
          margin: 10px 0 0 0;
        }
      }
    }
  }
}
</style>
